<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/5/27
 * Time: 14:29
 */

namespace Home\Controller;


use Common\Utils\WeChatUtils;
use Home\Logic\MoneyLogLogic;
use Home\Logic\OrderLogic;
use Home\Logic\UserLogic;
use Home\Logic\WithdrawalsLogic;
use Think\Controller;
use Think\Log;

class MeController extends BaseController
{
    private static $_cash_validate = array(
        array('money', 'require', '提现金额不能为空！', 1, 'regex', 3),
        array('bank_name', 'require', '银行名称不能为空！', 1, 'regex', 3),
        array('account_bank', 'require', '银行账户不能为空！', 1, 'regex', 3),
        array('account_name', 'require', '账户名称不能为空！', 1, 'regex', 3),
    );

    public function index(){
        $this->assign('page_str','me');
        $user=$this->getUser();
//        $user = D('Users')->where(array('user_id'=>$user['user_id']))->find();
//        if($user)
//            $this->assign('user',$user);
        $logic = new OrderLogic();
        $unReadOrderNum = $logic->getUnReadOrderNum();
        //查找成为代理商最低金额
        $lowMoney = M('Config')->where(array("name= 'agent_recharge'"))->getField('value');
        $this->assign('lowMoney', $lowMoney);
        $this->assign('unReadOrderNum',$unReadOrderNum);
        $this->assign('type', $user['user_type']);
        $this->display();
    }


    public function test(){
        $APPID = C('APPID');
        $APPSECRET = C('APPSECRET');
        $TOKEN = C('TOKEN');
        $utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
        $utils->sendAdminTemplateMessage(null,null);
    }



    //获取该用户地址列表
    public function address(){

        $user = $this->getUser();
        $addressList = M('UserAddress')->where(array('user_id'=>$user['user_id']))->select();

   /*     foreach ($addressList as $key => $val){
            $addressList[$key] = $this->getAddress($val);
        }*/
        $this->assign('addressList', $addressList);
        $this->assign('count',count($addressList));
        $this->display();

    }

    public function addressUI(){
        $address_id = I('get.address_id');
        $order_id = I('order_id');
        $user = $this->getUser();
        $address = array();
        if($address_id)
        {
            $address = M('UserAddress')->where(array('address_id'=> $address_id, 'user_id'=>$user['user_id']))->find();
        }

        $this->assign('order_id', $order_id);
        $this->assign('address', $address);
        $this->display('add_address');

    }

    public  function addEditAddress(){
//        Log::write();
        $id = I('post.address_id');
        $user = $this->getUser();
        $type = $id > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
//        $this->ajaxReturn(array('status'=>-1, 'msg'=>$id));
        $address = D('UserAddress');

        C('TOKEN_ON',false);
        if (!$address->create(I('post.'), $type))// 根据表单提交的POST数据创建数据对象
        {

            //  编辑
            $error = $address->getError();
            $error_msg = array_values($error);
            $return_arr = array(
                'status' => -1,
                'msg' => '操作失败',
                'data' => $error,
            );
            $this->ajaxReturn($return_arr);
        } else {
            if(!check_mobile($address->mobile))
                $this->ajaxReturn(array('status'=>-1, 'msg'=>'手机号出错', 'data'=>$address->mobile));
            $address->user_id = $user['user_id'];
//            $address->user_id = 0;
            if ($type == 2) {
                if($address->is_default == 1)
                    $this->setDefault($address->address_id, $address->user_id);
                $address->save(); // 写入数据到数据库
            } else {

                //检查是否是第一条如果是则设为默认地址
                $count = M('UserAddress')->where(array('user_id'=>$user['user_id']))->count();
                $goods_id = $insert_id = $address->add(); // 写入数据到数据库
                if(!$count)
                    $this->setDefault($goods_id, $user['user_id']);
                else if($address->is_default == 1)
                    $this->setDefault($goods_id, $user['user_id']);
            }
        }

        $return_arr = array(
            'status' => 1,
            'msg' => '操作成功',
//            'data' => array('url' => U('Admin/Goods/goodsList')),
        );
        $this->ajaxReturn($return_arr);

    }

    //删除地址
    public function delAddress(){

        $id = I('get.id');
        if($id)
        {

            M('UserAddress')->where(array('address_id'=>$id))->delete();
            $this->ajaxReturn(array('status'=>1, 'msg'=>'删除成功'));

        }
    }


    //设置默认地址
    public function setDefaultAddress(){
        $user = $this->getUser();
        $addressId = I('id');
//        $model = M('UserAddress');


        $this->ajaxReturn($this->setDefault($addressId, $user['user_id']));
    }

/*    public function getAddressById(){

        $id = I('id');
        $address = M('UserAddress')->where(array('address_id'=>$id))->find();
        $address = $this->getAddress($address);

        $this->ajaxReturn(array('status'=>1, 'data'=>$address));
    }*/

    private function setDefault($addressId, $userId){
        $address_data = M('user_address')->where(array('address_id'=>$addressId))->find();
        if($address_data['is_default'] == 1)
            $res = array('status'=>-1, 'msg'=>'改地址已经是默认地址');
        else
        {
            $default_data = M('user_address')->where(array('user_id'=>$userId, 'is_default'=>1))->find();
            if($default_data)
            {

                $default_data['is_default'] = 0;
                M('user_address')->save($default_data);
            }
            $address_data['is_default'] = 1;
            $result = M('user_address')->save($address_data);
            $res = array('status'=>1, 'msg'=>'设置成功');
        }
        return $res;
    }


/*    private function getAddress($address){

        $address['city1'] = M('region')->where(array('id'=>$address['city']))->getField('name');
        $address['province1'] = M('region')->where(array('id'=>$address['province']))->getField('name');
        $address['district1'] = M('region')->where(array('id'=>$address['district']))->getField('name');
        $address['twon1'] = M('region')->where(array('id'=>$address['twon']))->getField('name');


        return  $address;

    }*/

    /**
     * 账单明细
     */
    public function accountOrder(){
        $this->display();
    }

    /**
     * ajax获取资金流动列表
     */
    public function moneyLog(){
        $user = $this->getUser();
        $logic = new MoneyLogLogic();
        $pagenum = I('pagenum','1');
        $pagesize = 20;
        $data = $logic->getMoneyLogList($user['user_id'],$pagenum,$pagesize);
        $this->assign('data',$data);
        $this->display();
    }

    /**
     * 跳转到我的二维码界面
     */
    public function goToQRCode(){
        //判断用户user_type若不是代理商则跳转到充值页面

     /*   if(!$user['user_type']){
            $this->redirect("Home/Me/agentUI");
        }*/
        self::jsSDK();//分享
        $user_id = I('user_id');
        if(!empty($user_id)) {
            $user_type = M('users')->where(array('user_id'=> $user_id))->getField('user_type');
            $this->assign('user_id', $user_id);
            $this->assign('type', $user_type);
        }else{
//            $user = session('user');
            $user = $this->getUser();
            $this->assign('user_id', $user['user_id']);
            $this->assign('type', $user['user_type']);
        }
//        $user = $this->getUser();
//        $this->assign('type', $user['user_type']);
        $this->display('qrcode');
    }

    /**
     * 跳转到我的伙伴界面
     */
    public function goToMyDownUser(){
        $user = $this->getUser();
        $logic = new UserLogic();
        $pagenum = I('pagenum','1');
        $pagesize = 10;
        $data = $logic->getLastOneList($user['user_id'],$pagenum,$pagesize);
        $this->assign('data',$data);
        $this->display('down_user');
    }

    /**
     * 跳转到提现界面
     */
    public function cash(){
        $user = $this->getUser();
        $this->assign('user_money',$user['user_money']);
        $this->display();
    }

    /**
     * ajax提现申请
     */
    public function ajaxCash(){
        $data['money'] = I('money');
        $data['bank_name'] = I('bank_name');
        $data['account_bank'] = I('account_bank');
        $data['account_name'] = I('account_name');
        if(empty($data['bank_name'])){
            $this->ajaxReturn(array('success' => false, 'message' => '银行名称不能为空！'));
        }
        if(empty($data['account_name'])){
            $this->ajaxReturn(array('success' => false, 'message' => '账户名称不能为空！'));
        }
        if(empty($data['account_bank'])){
            $this->ajaxReturn(array('success' => false, 'message' => '银行账户不能为空！'));
        }
        if(empty($data['money']) || !is_numeric($data['money']) || $data['money'] <0 ){
            $this->ajaxReturn(array('success' => false, 'message' => '请输入正确的提现金额！'));
        }
        if (!check_bank_card($data['account_bank'])) {
            $this->ajaxReturn(array('success' => false, 'message' => '请输入正确的银行账号'));
        }
        $user = $this->getUser();
        if($data['money'] > $user['user_money']){
            $this->ajaxReturn(array('success' => false, 'message' => '余额不足，不能提现！'));
        }
        $cashLogic = new WithdrawalsLogic();
        $status = $cashLogic->withdrawals($user['user_id'],$data);
        if($status == 1){
            $this->ajaxReturn(array('success'=>true,'message'=>'已经提交提现申请！'));
        }else if($status == 2){
            $this->ajaxReturn(array('success'=>false,'message'=>'对不起，您不能进行该操作！'));
        }else{
            $this->ajaxReturn(array('success'=>false,'message'=>'确认收货失败！'));
        }
    }

    public function withdrawalsLog(){
        $this->display('withdrawals_log');
    }


    public function ajaxWithdrawalsLog(){
        $user = $this->getUser();
        $logic = new WithdrawalsLogic();
        $pagenum = I('pagenum','1');
        $pagesize = 20;
        $data = $logic->getWithdrawalsList($user['user_id'],$pagenum,$pagesize);
        $this->assign('data',$data);
        $this->display('ajax_withdrawals_log');
    }

    public function problem(){
        $this->display();
    }

    public function speedList(){
        $this->display();
    }


    public function agentUI(){
        $user = $this->getUser();
        if($user['user_type'] == 0) {
            $lowMoney = M('config')->where(array('name' => 'agent_recharge'))->getField('value');
            $this->assign('lowMoney', $lowMoney);
            $this->assign('type', 0);
        }
        else
            $this->assign('type', 1); //判断是否是代理商若不是则不要显示充值入口
        $this->display('agentUI');

    }

    public function  agent(){
        $user = $this->getUser();
        $userList = array();
     /*   if(!$user['user_type'])
            $this->redirect('/Home/Me/agentUI');*/
        //获取下级用户
        $this->assign('type', $user['user_type']);
        $userList['oneUserList'] = M('users')->where(array('first_leader'=> $user['user_id'], 'user_type'=>1))->select();

        //获取二级用户
        foreach ($userList['oneUserList'] as $key => $val) {
            $twoUserList = M('users')->where(array('first_leader' => $val['user_id'], 'user_type' => 1))->select();
            foreach ($twoUserList as $k => $v){
                $userList['twoUserList'][] = $v;
            }
        }
        //获取第三级用户
        foreach ($userList['twoUserList'] as $key => $val){
            $threeUserList = M('users')->where(array('first_leader' => $val['user_id'], 'user_type' => 1))->select();
            foreach ($threeUserList as $k => $v){
                $userList['threeUserList'][] = $v;
            }
        }
        $this->assign('oneUser', $user);
        $this->assign('userList', $userList);
        $this->display();

    }

    public function  recharge(){
        $lowMoney = M('config')->where(array('name' => 'agent_recharge'))->getField('value');
        $this->assign('lowMoney', $lowMoney);
        $this->display();

    }
    //展示代理商的商品价格
    public function  agentPrice(){
        $user = $this->getUser();
        /*if(!$user['user_type']){
            $this->redirect("Home/Me/agentUI");
            return ;
        }*/
        $this->assign('type', $user['user_type']);
        $this->display('agentPrice');

    }

}